package cloud.security.service;

import cloud.security.utils.CacheConstants;
import cloud.security.utils.Constants;
import cloud.security.vo.SecurityUser;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Component
public class CloudTokenService {
    Map<String,SecurityUser> tokenCache = new HashMap<>();

    @Value("${token.secret}")
    private String secret;
    @Value("${token.header}")
    private String header;
    @Value("${token.expireTime}")
    private int expireTime;

    protected static final long MILLIS_SECOND = 1000;

    protected static final long MILLIS_MINUTE = 60 * MILLIS_SECOND;

    /**
     * 创建token
     * @param securityUser
     * @return
     */
    public String createToken(SecurityUser securityUser){
        String token = UUID.randomUUID().toString();
        securityUser.setToken(token);
        refreshToken(securityUser);

        Map<String, Object> claims = new HashMap<>();
        claims.put(Constants.LOGIN_USER_KEY, token);
        return createToken(claims);
    }

    /**
     * jwt生成token
     * @param claims
     * @return
     */
    private String createToken(Map<String, Object> claims) {
        return Jwts.builder()
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS512, secret).compact();
    }

    /**
     * 刷新token
     * @param securityUser
     */
    private void refreshToken(SecurityUser securityUser) {

        securityUser.setLoginTime(System.currentTimeMillis());
        // 设置过期时间
        securityUser.setExpireTime(securityUser.getLoginTime() + expireTime * MILLIS_MINUTE);
        // 缓存token
        String userKey = getTokenKey(securityUser.getToken());
        tokenCache.put(userKey,securityUser);


    }


    public SecurityUser getLoginUser(HttpServletRequest request) {
        String token = getToken(request);
        Claims claims = parseToken(token);
        // 解析对应的权限以及用户信息
        String uuid = (String) claims.get(Constants.LOGIN_USER_KEY);
        String userKey = getTokenKey(uuid);
        SecurityUser securityUser = tokenCache.get(userKey);
        return securityUser;
    }

    /**
     * 验证令牌有效期，相差不足20分钟，自动刷新缓存
     *
     * @param token 令牌
     * @return 令牌
     */
    public void verifyToken(SecurityUser securityUser) {
        long expireTime = securityUser.getExpireTime();
        if (expireTime != -1l) {
            long currentTime = System.currentTimeMillis();
            if (expireTime - currentTime <= 20) {
                refreshToken(securityUser);
            }
        }

    }


    /**
     * 从令牌中获取数据声明
     *
     * @param token 令牌
     * @return 数据声明
     */
    private Claims parseToken(String token) {
        return Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();
    }

    /**
     * 获取请求token
     *
     * @param request
     * @return token
     */
    private String getToken(HttpServletRequest request) {
        String token = request.getHeader(header);
        if (token!=null && token!="" && token.startsWith(Constants.TOKEN_PREFIX)) {
            token = token.replace(Constants.TOKEN_PREFIX, "");
        }
        return token;
    }

    private String getTokenKey(String uuid) {
        return CacheConstants.LOGIN_TOKEN_KEY + uuid;
    }
}
